package top.i51213.fastaction.action.pdf;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class MyPdfReader extends PdfReader {
    public MyPdfReader(final String filename) throws IOException {
        super(filename);
    }

    public MyPdfReader(final byte[] bytes) throws IOException {
        super(bytes);
    }

    public MyPdfReader(final InputStream is) throws IOException {
        super(is);
    }

    public void decryptOnPurpose() {
        encrypted = false;
    }
    public void copyToAndClose(OutputStream outputStream){
        this.decryptOnPurpose();
        Document document = new Document();
        try {
            PdfCopy pdfCopy = new PdfCopy(document, new BufferedOutputStream(outputStream));
            pdfCopy.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
            document.open();
            pdfCopy.addDocument(this);
            this.close();
            pdfCopy.close();
            document.close();
        }catch (Exception ignored){
            ignored.printStackTrace();
        }
    }
    public static void openAndCopyTo(InputStream inputStream,OutputStream outputStream) throws IOException {
        MyPdfReader reader=new MyPdfReader(inputStream);
        reader.copyToAndClose(outputStream);
    }
    public static void openAndCopyTo(InputStream inputStream,String outputFilename) throws IOException {
        openAndCopyTo(inputStream,new FileOutputStream(outputFilename));
    }
}